package be.kuleuven.mume.paginas;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import be.kuleuven.mume.R;
import be.kuleuven.mume.arrayAdapters.AntwoordArrayAdapter;
import be.kuleuven.mume.framework.Antwoord;
import be.kuleuven.mume.framework.Vraag;
import be.kuleuven.mume.hulpklassen.DataFetcher;
import be.kuleuven.mume.hulpklassen.HttpHelper;
import be.kuleuven.mume.hulpklassen.JSONHandler;
import be.kuleuven.mume.hulpklassen.JSONHelper;
import be.kuleuven.mume.hulpklassen.RetainListActivity;
import be.kuleuven.mume.hulpklassen.JSONParser.AntwoordenParser;
import be.kuleuven.mume.listProxys.LastCellLoadingProxy;

public class AntwoordenPagina extends RetainListActivity<Antwoord> implements OnItemClickListener {
	private static final int AntwoordEdit_Activity = 0;
	private static final int AntwoordADD_Activity = 1;
	private static final int ANTWOORD_ID = Menu.FIRST;
	
	//private DbAdapter mDbHelper = new DbAdapter(this);
	//private Cursor mVragenCursor;
	private TextView mVraag;
	private Vraag vraag;
	private ListView mAntwoorden;
	private AntwoordArrayAdapter adapter;
	private LastCellLoadingProxy loadingProxy;
	private List<Antwoord> antwoorden;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    	setContentView(R.layout.antwoorden_pagina);
    	if ( customTitleSupported ) {
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
        }
    	
    	Bundle extras = getIntent().getExtras();
    	vraag = (Vraag)extras.get(Vraag.VRAAG);
    	
    	final TextView myTitleText = (TextView) findViewById(R.id.myTitle);
        if ( myTitleText != null ) {
            myTitleText.setText(vraag.getSubject());
        }

    	//mDbHelper = new DbAdapter(this);
    	
    	mVraag = (TextView) findViewById(R.id.vraag);
    	mVraag.setText(vraag.getText());
    	
    	
    	mAntwoorden = (ListView) findViewById(R.id.antwoordenlijst);
    	mAntwoorden.setOnItemClickListener(this);
    	
		antwoorden = new ArrayList<Antwoord>();
		AntwoordenParser parser = new AntwoordenParser();
		//String jString = HttpHelper.getStringContent(, this.getBaseContext());
		new DataFetcher<Antwoord>(parser, Antwoord.getUrl(vraag.getId()), 
				mAntwoorden, antwoorden, this.getBaseContext()){
			@Override
			public void DataReceived() {
				if(!hasMoreData())
					loadingProxy.setIsLoading(false);
				adapter.notifyDataSetChanged();
			}
		};
		adapter = new AntwoordArrayAdapter(this, antwoorden);
		loadingProxy = new LastCellLoadingProxy(adapter);
		loadingProxy.noDataString_ID = R.string.geen_antwoorden;
		
		mAntwoorden.setAdapter(loadingProxy);
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if(adapter.getCount() > position) { 
			Antwoord a = adapter.getItem(position);
		        
			 Intent i = new Intent(this, AntwoordEditPagina.class);
			 i.putExtra(Antwoord.ANTWOORD, a);
			 i.putExtra(Vraag.VRAAG, vraag);
			 
			 startActivityForResult(i, AntwoordEdit_Activity);
		}
	 }
	
	
	/*private void toonAntwoorden() {
		//Gebruik SQLite
//		mDbHelper.open();
//		mVragenCursor = mDbHelper.fetchAllAntwoorden(vraagId);
//		startManagingCursor(mVragenCursor);
//
//		// Create an array to specify the fields we want to display in the list (only TITLE)
//		String[] from = new String[]{DbAdapter.KEY_ANTWOORD};
//
//		// and an array of the fields we want to bind those fields to (in this case just text1)
//		int[] to = new int[]{R.id.text1};
//
//		// Now create a simple cursor adapter and set it to display
//		SimpleCursorAdapter notes = 
//			new SimpleCursorAdapter(this, R.layout.rij_simpel, mVragenCursor, from, to);
//		mAntwoorden.setAdapter(notes);
//		mDbHelper.close();
	}*/
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, ANTWOORD_ID,0, R.string.menu_antwoord);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case ANTWOORD_ID:
            createAntwoord();
            return true;
        }
        
        return super.onMenuItemSelected(featureId, item);
    }
    
    private void createAntwoord() {
    	Intent i = new Intent(this, AntwoordEditPagina.class);
    	i.putExtra(Vraag.VRAAG, vraag);
    	startActivityForResult(i, AntwoordADD_Activity);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	if(intent == null) // When user presses android-back button the intent will be null
			 return;
    	
    	Bundle extras = intent.getExtras();
    	String url;
    	Antwoord a = (Antwoord)extras.get(Antwoord.ANTWOORD);
    	switch(requestCode) {
    	case AntwoordADD_Activity:
    		url = Antwoord.URL_ADD;
    		postAntwoord(a, url);
    		break;
    	case AntwoordEdit_Activity:
    		url = Antwoord.URL_UPDATE;
    		postAntwoord(a, url);
    	}
    	
    }

	private void postAntwoord(Antwoord antwoord, String url) {
		JSONObject obj = JSONHelper.createAntwoord(antwoord);
		JSONHandler h = new JSONHandler() {
			
			@Override
			public void handelJSON(JSONObject obj) {
				if(obj.has("error"))
					Toast.makeText(AntwoordenPagina.this, R.string.serverError, 10).show();
			}
		};
		HttpHelper.doPostInThread(url, obj, this.getBaseContext(), h);
		if(!antwoorden.contains(antwoord)){
			antwoorden.add(0,antwoord);
			loadingProxy.refresh();
		}
		adapter.notifyDataSetChanged();
	}
    
}
